package com.gomcarter.frameworks.base.common;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * Created by daibing on 2022/10/8.
 */
public class CustomLocalDateTimeUtils extends CustomDateUtils {
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String TIME_PATTERN = "HH:mm:ss";
    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_PATTERN);
    public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern(TIME_PATTERN);

    public static LocalTime fromString2LocalTime(String dateStr) {
        return Optional.ofNullable(dateStr)
                .filter(str -> !str.isEmpty())
                .map(str -> {
                    String text = CustomStringUtils.replaceEach(dateStr, new String[]{"/", "\n",}, new String[]{"-", "",});
                    DateTimeFormatter formatter = getFormatter(text);
                    return LocalTime.parse(text, formatter);
                })
                .orElse(null);
    }

    public static LocalDate fromString2LocalDate(String dateStr) {
        return Optional.ofNullable(dateStr)
                .filter(str -> !str.isEmpty())
                .map(str -> {
                    String text = CustomStringUtils.replaceEach(dateStr, new String[]{"/", "\n",}, new String[]{"-", "",});
                    DateTimeFormatter formatter = getFormatter(text);
                    return LocalDate.parse(text, formatter);
                })
                .orElse(null);
    }

    public static LocalDateTime fromString2LocalDateTime(String dateStr) {
        return Optional.ofNullable(dateStr)
                .filter(str -> !str.isEmpty())
                .map(str -> {
                    String text = CustomStringUtils.replaceEach(dateStr, new String[]{"/", "\n",}, new String[]{"-", "",});
                    DateTimeFormatter formatter = getFormatter(text);
                    return LocalDateTime.parse(text, formatter);
                })
                .orElse(null);
    }

    private static DateTimeFormatter getFormatter(String dateStr) {
        boolean containDate = CustomStringUtils.contains(dateStr, "-");
        boolean containTime = CustomStringUtils.contains(dateStr, ":");
        if (containDate && containTime) {
            return DATE_TIME_FORMATTER;
        }
        if (containDate) {
            return DATE_FORMATTER;
        }
        if (containTime) {
            return TIME_FORMATTER;
        }
        return DATE_TIME_FORMATTER;
    }
}
